<template>
  <el-dialog v-model="visible" title="打印单据" :width="isLargeScreen ? '80%' : '95%'" :fullscreen="!isLargeScreen" @close="handleClose">
    <div class="flex flex-col h-[calc(100vh-180px)]">
      <!-- 模板选择区域 -->
      <div class="mb-6">
        <h3 class="text-lg font-medium mb-3">选择打印模板</h3>

        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 max-h-48 overflow-y-auto panel-scroll pr-2">
          <div
            v-for="template in savedTemplates"
            :key="template.id"
            class="border rounded-lg p-3 cursor-pointer hover:border-primary hover:bg-primary/5 transition-all"
            :class="selectedTemplateId === template.id ? 'border-primary bg-primary/5' : ''"
            @click="selectedTemplateId = template.id"
          >
            <div class="flex justify-between items-start">
              <div>
                <h4 class="font-medium">{{ template.name }}</h4>
                <p class="text-sm text-gray-500 mt-1">{{ template.paperSize | formatPaperSize }} · {{ template.orientation | formatOrientation }}</p>
                <p class="text-xs text-gray-400 mt-1">创建于 {{ template.createdAt | formatDate }}</p>
              </div>
              <el-button
                icon="Delete"
                size="mini"
                circle
                type="text"
                class="text-gray-400 hover:text-danger"
                @click.stop="deleteTemplate(template.id)"
              />
            </div>
          </div>

          <div v-if="savedTemplates.length === 0" class="col-span-full py-10 text-center">
            <p class="text-gray-500">暂无保存的模板</p>
            <p class="text-sm text-primary mt-2 cursor-pointer" @click="gotoDesigner">去创建新模板</p>
          </div>
        </div>

        <div class="mt-4 flex gap-2">
          <input type="file" ref="importTemplateFile" accept=".json" class="hidden" @change="handleTemplateImport" />
          <el-button type="primary" icon="Upload" size="small" @click="importTemplateFile.click()"> 导入模板文件 </el-button>
          <el-button type="default" icon="Edit" size="small" @click="gotoDesigner"> 设计新模板 </el-button>
        </div>
      </div>

      <!-- 数据输入区域 -->
      <div class="mb-6 flex-1 overflow-y-auto panel-scroll">
        <h3 class="text-lg font-medium mb-3">填写单据信息</h3>

        <template v-if="selectedTemplate">
          <el-form :model="formData" label-width="100px" size="small">
            <el-form-item label="订单编号">
              <el-input v-model="formData.orderNo" placeholder="请输入订单编号"></el-input>
            </el-form-item>

            <el-form-item label="订单日期">
              <el-date-picker v-model="formData.orderDate" type="date" placeholder="选择日期" value-format="YYYY-MM-DD"></el-date-picker>
            </el-form-item>

            <el-divider content="客户信息"></el-divider>

            <el-form-item label="客户名称">
              <el-input v-model="formData.customer.name" placeholder="请输入客户名称"></el-input>
            </el-form-item>

            <el-form-item label="联系电话">
              <el-input v-model="formData.customer.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>

            <el-form-item label="客户地址">
              <el-input v-model="formData.customer.address" placeholder="请输入客户地址"></el-input>
            </el-form-item>

            <el-divider content="商品信息"></el-divider>

            <el-table v-model:data="formData.products" border style="width: 100%; margin-bottom: 10px">
              <el-table-column prop="name" label="商品名称" min-width="180">
                <template #default="scope">
                  <el-input v-model="scope.row.name" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="100">
                <template #default="scope">
                  <el-input v-model.number="scope.row.quantity" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="单价" width="100">
                <template #default="scope">
                  <el-input v-model.number="scope.row.price" size="small"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="金额" width="100">
                <template #default="scope">
                  <span>{{ (scope.row.quantity * scope.row.price).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button
                    icon="Delete"
                    size="mini"
                    type="text"
                    class="text-gray-400 hover:text-danger"
                    @click="formData.products.splice(scope.$index, 1)"
                  />
                </template>
              </el-table-column>
            </el-table>

            <el-button type="text" icon="Plus" size="small" @click="addProduct"> 添加商品 </el-button>
          </el-form>
        </template>

        <div v-else class="py-10 text-center">
          <p class="text-gray-500">请先选择一个打印模板</p>
        </div>
      </div>

      <!-- 底部操作区 -->
      <div class="mt-4 flex justify-end gap-2">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="printDocument" :loading="printLoading"> <i class="fa fa-print mr-1"></i> 打印单据 </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';

// 外部控制弹窗显示
const visible = ref(false);
const printLoading = ref(false);
const router = useRouter();

// 模板相关
const savedTemplates = ref([]);
const selectedTemplateId = ref(null);
const selectedTemplate = computed(() => {
  return savedTemplates.value.find((t) => t.id === selectedTemplateId.value) || null;
});

// 表单数据
const formData = reactive({
  orderNo: '',
  orderDate: new Date().toISOString().split('T')[0],
  customer: {
    name: '',
    phone: '',
    address: ''
  },
  products: [{ name: '', quantity: 1, price: 0 }]
});

// 屏幕尺寸判断
const isLargeScreen = computed(() => {
  return window.innerWidth >= 1024;
});

// 初始化
onMounted(() => {
  loadSavedTemplates();
});

// 加载保存的模板
function loadSavedTemplates() {
  const templates = localStorage.getItem('printTemplates');
  if (templates) {
    savedTemplates.value = JSON.parse(templates);
  }
}

// 模板操作
function deleteTemplate(id) {
  if (confirm('确定要删除这个模板吗？')) {
    const index = savedTemplates.value.findIndex((t) => t.id === id);
    if (index !== -1) {
      savedTemplates.value.splice(index, 1);
      localStorage.setItem('printTemplates', JSON.stringify(savedTemplates.value));

      if (selectedTemplateId.value === id) {
        selectedTemplateId.value = savedTemplates.value.length > 0 ? savedTemplates.value[0].id : null;
      }
    }
  }
}

function handleTemplateImport(event) {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const templateData = JSON.parse(e.target.result);

      // 转换为完整模板格式
      const newTemplate = {
        id: Date.now(),
        name: templateData.name || '导入的模板',
        createdAt: new Date().toISOString(),
        paperSize: templateData.paperSize || 'a4',
        orientation: templateData.orientation || 'portrait',
        controls: templateData.controls || []
      };

      savedTemplates.value.push(newTemplate);
      localStorage.setItem('printTemplates', JSON.stringify(savedTemplates.value));
      selectedTemplateId.value = newTemplate.id;

      alert('模板导入成功');
    } catch (error) {
      alert('导入失败，文件格式不正确');
      console.error(error);
    }
  };
  reader.readAsText(file);

  // 重置input
  event.target.value = '';
}

// 商品操作
function addProduct() {
  formData.products.push({ name: '', quantity: 1, price: 0 });
}

// 打印操作
function printDocument() {
  if (!selectedTemplate.value) {
    alert('请先选择一个模板');
    return;
  }

  if (!validateForm()) {
    return;
  }

  printLoading.value = true;

  // 创建打印窗口
  const printWindow = window.open('', '_blank');

  // 生成打印内容
  const printContent = generatePrintContent();

  // 设置打印样式
  const isLandscape = selectedTemplate.value.orientation === 'landscape';
  let paperStyle = '';

  if (isLandscape) {
    paperStyle = '@page { size: A4 landscape; margin: 1.5cm; }';
  }

  // 写入打印窗口
  printWindow.document.write(`
    <html>
      <head>
        <title>打印预览 - ${formData.orderNo}</title>
        <style>
          ${paperStyle}
          body { font-family: "SimSun", "宋体", serif; font-size: 12px; }
          table { width: 100%; border-collapse: collapse; margin-bottom: 10px; }
          th, td { border: 1px solid #ccc; padding: 5px 8px; }
          th { background-color: #f5f5f5; }
          .text-center { text-align: center; }
          .text-right { text-align: right; }
          .font-bold { font-weight: bold; }
        </style>
      </head>
      <body>
        ${printContent}
      </body>
    </html>
  `);

  printWindow.document.close();

  // 等待页面加载完成后打印
  printWindow.onload = () => {
    printWindow.print();
    printLoading.value = false;
    // 打印后关闭窗口（可选）
    // setTimeout(() => printWindow.close(), 1000);
  };
}

// 生成打印内容
function generatePrintContent() {
  // 创建临时容器来生成HTML
  const tempContainer = document.createElement('div');

  // 遍历模板控件并生成内容
  selectedTemplate.value.controls.forEach((control) => {
    const controlElement = document.createElement('div');

    // 设置控件样式
    controlElement.style.position = 'relative';
    controlElement.style.margin = `${control.y}mm 0 0 ${control.x}mm`;
    controlElement.style.width = control.width ? `${control.width}mm` : 'auto';
    controlElement.style.height = control.height ? `${control.height}mm` : 'auto';
    controlElement.style.textAlign = control.align || 'left';
    controlElement.style.color = control.color || '#000';
    controlElement.style.fontSize = control.fontSize ? `${control.fontSize}px` : '14px';
    controlElement.style.fontWeight = control.bold ? 'bold' : 'normal';
    controlElement.style.fontStyle = control.italic ? 'italic' : 'normal';
    controlElement.style.textDecoration = control.underline ? 'underline' : 'none';
    controlElement.style.border = control.borderWidth ? `${control.borderWidth}px solid ${control.borderColor || '#000'}` : 'none';

    // 根据控件类型生成内容
    switch (control.type) {
      case 'text':
        controlElement.innerHTML = `<p>${control.content || ''}</p>`;
        break;

      case 'heading':
        controlElement.innerHTML = `<h2>${control.content || ''}</h2>`;
        break;

      case 'orderInfo':
        controlElement.innerHTML = `
          <p class="text-gray-500">订单信息</p>
          <p>订单编号: ${formData.orderNo}</p>
          <p>订单日期: ${formData.orderDate}</p>
        `;
        break;

      case 'customerInfo':
        controlElement.innerHTML = `
          <p class="text-gray-500">客户信息</p>
          <p>客户名称: ${formData.customer.name}</p>
          <p>电话: ${formData.customer.phone}</p>
          <p>地址: ${formData.customer.address}</p>
        `;
        break;

      case 'productTable':
        let productRows = '';
        formData.products.forEach((product, index) => {
          const amount = (product.quantity * product.price).toFixed(2);
          productRows += `
            <tr>
              <td>${index + 1}</td>
              <td>${product.name}</td>
              <td class="text-right">${product.quantity}</td>
              <td class="text-right">${product.price.toFixed(2)}</td>
              <td class="text-right">${amount}</td>
            </tr>
          `;
        });

        // 计算总计
        const totalAmount = formData.products
          .reduce((sum, product) => {
            return sum + product.quantity * product.price;
          }, 0)
          .toFixed(2);

        productRows += `
          <tr>
            <td colspan="4" class="text-right font-bold">总计:</td>
            <td class="text-right font-bold">${totalAmount}</td>
          </tr>
        `;

        controlElement.innerHTML = `
          <p class="text-gray-500 mb-2">商品明细</p>
          <table>
            <thead>
              <tr>
                <th>序号</th>
                <th>商品名称</th>
                <th class="text-right">数量</th>
                <th class="text-right">单价</th>
                <th class="text-right">金额</th>
              </tr>
            </thead>
            <tbody>
              ${productRows}
            </tbody>
          </table>
        `;
        break;

      // 其他控件类型处理...
      default:
        controlElement.innerHTML = '';
    }

    tempContainer.appendChild(controlElement);
  });

  return tempContainer.innerHTML;
}

// 表单验证
function validateForm() {
  if (!formData.orderNo) {
    alert('请输入订单编号');
    return false;
  }

  if (!formData.customer.name) {
    alert('请输入客户名称');
    return false;
  }

  if (formData.products.every((p) => !p.name)) {
    alert('请至少添加一个商品');
    return false;
  }

  return true;
}

// 导航到设计页面
function gotoDesigner() {
  visible.value = false;
  router.push('/template-designer');
}

// 弹窗控制
function handleClose() {
  visible.value = false;
}

// 过滤器
const formatPaperSize = (size) => {
  const sizeMap = {
    'a4': 'A4',
    'letter': 'Letter'
  };
  return sizeMap[size] || size;
};

const formatOrientation = (orientation) => {
  return orientation === 'portrait' ? '纵向' : '横向';
};

const formatDate = (dateString) => {
  const date = new Date(dateString);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 暴露给父组件的方法
defineExpose({
  open: () => {
    visible.value = true;
    loadSavedTemplates();
  }
});
</script>

<style scoped>
/* 样式省略 */
</style>
